import { Component, Input, OnInit } from '@angular/core';
import { SFSchema } from '@delon/form';
import { ApiService } from '@core/services/api';
import { HttpClient } from '@angular/common/http';
import { NzMessageService, NzModalRef } from 'ng-zorro-antd';
import { reader }from '../../../../../assets/js/rdapi.js'

@Component({
  selector: 'app-card-add',
  templateUrl: './card-add.component.html',
  styles: []
})
export class CardAddComponent implements OnInit {
  showForm = true;
  param: any;
  g_device:string="00";
  g_isOpen:boolean= false;
  g_wantFunc:number=0;

  cardNumber="";
  desNum="";
  readData=0;//读出的数据
  pwd="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";//密钥
  num=0;//web认证的次数 现在设置为两次，两次不成功的话就不再继续
  inNum=0;//代表创建两个二进制文件
  select=0;//复位
  random=0;//获取随机数
  delfile=0;//擦除MF下的数据
  createSK=0;//创建密钥文件
  sk=0;//增加外部认证密钥
  createTwo=0;//创建二进制文件
  writeFile=0;//写入二进制文件
  readFile=0;//读取二进制文件
  schema: SFSchema = {
    properties: {
      cardId: {
        type: 'string',
        title: '卡号',
      },
      cardNo: {
        type: 'string',
        title: '虚拟卡号',
      },
      cardCode: {
        type: 'string',
        title: '卡编号',
      },
      cardType: {
        type: 'string',
        title: '卡类型',
        enum: [
          {label: 'IC卡', value:'1'},
          {label: 'CPU卡', value:'2'},
          {label: '身份证', value:'3'},
          {label: '居住证', value:'4'},
          {label: '银行卡', value:'5'},
          {label: 'APP', value:'6'},
        ],
      }
    },
    required: ['cardId','cardNo', 'cardCode', 'cardType']
  }

  formSubmit(data) {
    const body: any = {
      id: data.cardId,
      cardNo: data.cardNo,
      cardCode: data.cardCode,
      cardType: data.cardType,
    };
    const url = this.api.doorCard.save.url;
    const method =this.api.doorCard.save.method;
    this.http.request<any>(method, url,  { body}).subscribe(res => {
      console.log(res)
      if (res.status === '200' || res.status === '201') {
        this.msg.success('操作成功');
        this.modalRef.triggerOk();
      } else {
        this.msg.error(res.message)
      }
    })

  }
  constructor(
    private api: ApiService,
    private http: HttpClient,
    private msg: NzMessageService,
    private modalRef: NzModalRef
  ) { }

  ngOnInit() {
    if(reader.SocketOpen){
      this.connect();
    }else{
      reader.createSocket();
      setTimeout(()=>{
        this.connect();
      },200)
    }
    reader.onResult((rData:any)=>{
      console.log(rData)
      this.inNum++;
      if(rData.strCmdCode == "1203"){
        let str=rData.strData;
        let a=str.substring(str.length-4,str.length);
        if(a != "9000" ){//证明出现错误
          if(this.delfile == 1){//代表密钥错误，需要用新的密钥，然后获取并发送八字节加密数据
            this.select=1;
            this.delfile=0;
            this.pwd="0123321456654789987ABCDEFFEDCBC1";//用新的密钥去认证
            if(this.num == 2){//如果认证两次依然错误的话，则不再继续
              this.msg.error('密钥错误')
              return;
            }
          }else{
            return;
          }
        }
      }

      if(this.readData == 1){//代表读取二进制文件
       let n=rData.strData.slice(0,16);
       this.param={
         cardId:this.cardNumber,
         cardNo:n
       }
       this.checkCard()//检查卡是否已经被绑定
       this.readData=0;
      }
      
      if(this.select == 1 ){//获取随机数 已复位
        this.getRandom();
        this.random=1;
        this.select=0;
      }else if(this.random == 1 ){//发送八字节加密数据
        //获取八字节加密数据，然后发送八字节加密数据
        this.getDesNum(rData.strData.slice(0,16)).then((res)=>{
          this.getNumber();
        });
        this.num++;
        this.delfile=1;
        this.random=0;
      }else if(this.delfile == 1 ){
        this.delData();
        this.createSK=1;
        this.delfile=0;
      }else if(this.createSK == 1 ){
        this.createFile();
        this.sk=1;
        this.createSK=0;
      }else if(this.sk == 1 ){
        this.addSK();
        this.createTwo=1;
        this.sk=0;
      }else if(this.createTwo == 1 ){
        this.createHex();
        this.writeFile=1;
        this.createTwo=0;
        this.inNum=0;
      }else if(this.writeFile == 1 && this.inNum == 2){//index=2代表两个二进制文件已经创建完成，然后执行写二进制文件
        this.writeHex();
        this.writeFile=0;
        this.readFile=1;
        this.inNum=0;
      }else if(this.readFile == 1 && this.inNum == 2){//读取二进制文件  index=2代表两个二进制文件已经写入完成，可以执行读二进制文件
        this.readHex();
        this.readFile=0;
        this.readData=1;
      }


      switch(rData.strCmdCode){
        case "0007":
          if(rData.strStatus != "00"){
            this.msg.error("连接设备失败!");
          }else{
            this.g_isOpen=true;
            console.log("连接成功")
          }
          break;
        case "1001":
          if(rData.strStatus != "00"){
            return;
          }
          switch(this.g_wantFunc){
             case 1:
              reader.send(this.g_device + "1002"); //TyA_Anticollision
              break;
          }
          break;
        case "1002":
          if(rData.strStatus != "00"){
            return;
          }
          switch(this.g_wantFunc){
              case 1 :
                // this.validateForm.patchValue({
                //   cardNo:rData.strData+"00000000"
                // })
                // this.cardList.unshift({
                //   "cardNo":rData.strData
                // });
                // this.cardNo=rData.strData;
                // this.checkCard();
              break;
          }
          break;
          case "1202"://复位
						this.cardNumber=rData.strData.slice(0,8);
						console.log("选择MF");
						reader.send(this.g_device + "1203" + "00A40000023F00");//选择MF
						this.select=1;
					break;
      }
     
    })
  }
  ngOnDestroy(){
    reader.Disconnect();
  }

  //读卡或者输完卡号之后，检查此卡是否已经被绑定
  checkCard(){
    if(this.cardNumber == "" || this.cardNumber == undefined){
      return;
    }
    const that=this;
    this.http.get(this.api.doorCard.checkCard.url+this.cardNumber).subscribe((res:any)=>{
      console.log(res);
      if(res.status == 200){
        if(res.data != null && res.data.personId != "" && res.data.personId != null){
              this.msg.error("此卡已经被绑定!");
              setTimeout(function(){
                that.cardNumber="";
               that.param={
                 cardId:'',
                 cardNo:''
               }
              },1000);
          }
      }
    })
  }

  connect(){
    reader.send(this.g_device + "0007" + "00"); //Open the USB device with index number 0. (打开索引号为0的USB设备)
    reader.send(this.g_device + "0109" + "41"); //Set to ISO14443a working mode. (设置为ISO14443A工作模式)
    reader.send(this.g_device + "0108" + "01"); //Turn on the reader antenna. (打开读卡器天线)
    this.LedGreen();
    setTimeout(()=>{this.LedRed()},200);
    reader.send(this.g_device + "0106" + "10"); //Beeps. (蜂鸣提示)
  }
  /**
   * Turn on the green light
   * (亮绿灯)
  **/
  LedGreen()
  {
    reader.send(this.g_device + "0107" + "02"); 
  }
  
  /**
   * Turn on the red light
   * (亮红灯)
  **/
  LedRed()
  {
    reader.send(this.g_device + "0107" + "01"); 
  }
  
  
  read(){
    // if(this.g_isOpen != true){
    //   this.message.error("请连接读卡器!");
    //   return;
    // }
    this.num=0;
    this.selectMF();
  }
  
  //复位之后才能发送cos命令
  selectMF(){
    console.log("复位");
    console.log(1);
    this.select=0;
    reader.send(this.g_device + "1202" + "26");//复位
  }
  
  //获取四字节随机数
  getRandom(){
    console.log("获取八字节随机数")
    console.log(2);
    reader.send(this.g_device + "1203" + "0084000008");//获取四字节随机数
  }
  
  //发送八字节加密数据
  getNumber(){
    console.log("发送八字节加密数据");
    console.log(3);
    console.log(this.desNum)
    reader.send(this.g_device + "1203" + "0082000008" + this.desNum);
  }
  //擦除MF下的数据
  delData(){
    console.log("擦除MF下的数据");
    console.log(4);
    //擦除MF下的数据
    reader.send(this.g_device + "1203" + "800E000000");
  }
  //建立密钥文件
  createFile(){
    //建立密钥文件
    console.log("建立密钥文件");
    console.log(5);
    reader.send(this.g_device + "1203" + "80E00000073F005001F1FFFF");
  }
  //增加外部认证密钥
  addSK(){
    console.log("增加外部认证密钥");
    console.log(6);
    reader.send(this.g_device + "1203" + "80D401001539F0F1AADD"+"0123321456654789987ABCDEFFEDCBC1");
    //reader.send(g_device + "1203" + "80D401000D39F0F1AADD"+"FFFFFFFFFFFFFFFF");
  }
  //创建二进制文件
  createHex(){
    console.log("创建二进制文件");
    console.log(7);
    reader.send(this.g_device + "1203" +"80E0001F07280020F0F1FFFF");//31号文件
    reader.send(this.g_device + "1203" +"80E0001A07280020F0F1FFFF");//26号文件
    
  }
  //写二进制文件
  writeHex(){
    console.log("写二进制文件");
    console.log(8);
    this.getDesNum(this.cardNumber+"00000000").then((res)=>{
      console.log('虚拟卡号',this.desNum)
      reader.send(this.g_device + "1203" +"00D69F0008"+"8F4C3814C3B499A9");//31号文件
      reader.send(this.g_device + "1203" +"00D69A0008"+this.desNum);//26号文件
    })
   
  }
  //读二进制文件
  readHex(){
    console.log("读二进制文件");
    console.log(9);
    reader.send(this.g_device + "1203" +"00B09A0010");
  }
  
  //获取八字节加密数据
  getDesNum(randomNum){
   return  new Promise((resolve)=>{
      this.http.post("/core/door/card/desCard?data="+randomNum+"&password="+this.pwd,{}).subscribe((res:any)=>{
        console.log(res)
        this.desNum=res.data
        resolve(res.data)
      })
    })
  }
 
// //读卡
// readCpu(){
//   if(this.g_isOpen != true){
//     this.msg.error("请连接读卡器!");
//     return;
//   }
//   //Start read UID
//   reader.send(this.g_device + "1001" + "52"); //TyA_Request
//   this.g_wantFunc = 1;  
//   reader.send(this.g_device + "0106" + "10"); //Beeps. (蜂鸣提示)
// }

// //连接读卡器
// Connect(){
//     reader.send(this.g_device + "0007" + "00"); //Open the USB device with index number 0. (打开索引号为0的USB设备)
//     reader.send(this.g_device + "0109" + "41"); //Set to ISO14443a working mode. (设置为ISO14443A工作模式)
//     reader.send(this.g_device + "0108" + "01"); //Turn on the reader antenna. (打开读卡器天线)
//    this.LedGreen();
//    let that=this;
//     setTimeout(function(){that.LedRed()},200); 
//     reader.send(this.g_device + "0106" + "10"); //Beeps. (蜂鸣提示)
// }
// Disconnect(){
//   reader.send(this.g_device + "0009"); 
// }

// LedGreen(){
//  reader.send(this.g_device + "0107" + "02"); 
// }

// LedRed(){
//   reader.send(this.g_device + "0107" + "01"); 
// }

}
